package com.zlm.tcp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: 郑
 * 服务端
 * 1 建立服务的端口ServerSocket
 * 2 等待用户的连接accept
 * 3 接送用户消息
 */
public class TcpServerDemo1 {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;
        try {
            serverSocket = new ServerSocket(9999);
            //等待客户端连接
            socket = serverSocket.accept();
            //读取客户端消息
            is = socket.getInputStream();
            //管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len =is.read(buffer)) !=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(baos !=null){
                    baos.close();
                }
                if(is !=null){
                    is.close();
                }
                if(socket !=null){
                    socket.close();
                }
                if(serverSocket !=null){
                    serverSocket.close();
                }
                } catch (IOException e) {
                    e.printStackTrace();
            }
        }
    }
}
